﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http.Extensions;
using Infrastructure.ExternalService.Core.Responses;
using Newtonsoft.Json;

namespace Infrastructure.ExternalService.Core.Imp.Extensions
{
    public static class HttpResponseMessageExtension
    {
        public static async Task<T> ConvertToWrapResponse<T>(this HttpResponseMessage httpResponseMessage)
        {
            var resStr = await httpResponseMessage.Content.ReadAsStringAsync();
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                var wrapResponse = JsonConvert.DeserializeObject<WrapResponse>(resStr);
                if (wrapResponse.Code != ClientReturnCode.Success)
                {
                    throw new HttpProxyException(wrapResponse.Msg);
                }
                WrapResponse<T> ret = JsonConvert.DeserializeObject<WrapResponse<T>>(resStr);
                return ret.Data;
            }

            throw new HttpProxyException($"服务异常,StatusCode:{httpResponseMessage.StatusCode},URL:{httpResponseMessage.RequestMessage.RequestUri.PathAndQuery},Response:{resStr}");
        }

    }
}
